import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';

import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_driver/Order/WaybillDetails/CancelWaybill.dart';
import 'package:sph_driver/Order/WaybillDetails/PictureManagement.dart';
import 'package:sph_driver/Order/WaybillDetails/UploadPhotoPage.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../Message/SingleChatPage.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../http/NoLoadingPostApi.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import '../EvaluationPage.dart';
import '../WaybillDetails/UnconfirmedTransportationAgreement.dart';
import '../WaybillDetails/WaybillDetailsView.dart';
import 'dart:io';
import 'package:platform/platform.dart';
class RuningOrderList extends StatefulWidget {
  const RuningOrderList({super.key});

  @override
  State<RuningOrderList> createState() => _RuningOrderListState();
}

class _RuningOrderListState extends State<RuningOrderList> {
  double Latitude=0;
  double Longitude=0;
  List dataList=[];
  int pageNum=1;
  bool isLoading =false;
  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();
  bool _suc = false;
  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        showCallPhoneFirstDialog(context);
        // 权限被拒绝，但用户可以再次授权
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }

  Future _onRefresh() async {
    getAllOrderListAction();
  }

  @override
  void initState() {
    getAllOrderListAction();
    // TODO: implement initState
    super.initState();
    // _locationAction();
    // _startLocation();
    // getLocation();
  }
  //到达装货地
  Future<void> reachLoadPalce(String waybillId) async {

  }
  //到达卸货地
  Future<void> reachDownPalce(String waybillId) async {
    LoadingDialog.show(context);
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header +
          'api/waybill/waybill/driver/reachUnloadPalce',
      data: {
        "waybillId":waybillId,
        "flag":true,
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          LoadingDialog.hide(context);
          BrnToast.show("操作成功", context);
          getAllOrderListAction();

        } else {
          LoadingDialog.hide(context);
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
//出发打卡
  Future<void> departureCheckin(String waybillId) async {
    LoadingDialog.show(context);
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header +
          'api/waybill/waybill/driver/clockGo',
      data: {
        "waybillId":waybillId,

      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          LoadingDialog.hide(context);
          BrnToast.show("打卡成功", context);
          getAllOrderListAction();

        } else {
          LoadingDialog.hide(context);
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  //获取运单列表
  Future<void> getAllOrderListAction() async {
    NoLoadinggetApiManager.getData(
      context,
      'api/waybill/driver/waybill/page',
      {
        "pageNum": pageNum,
        "pageSize": 20,
        "category":2,
      },
          (responseData) {
        setState(() {
          if(pageNum==1){
            dataList = responseData['data']['records'];
          }else {
            if(responseData['data']['records'].isNotEmpty) {
              dataList.add(responseData['data']['records']);
            }else{
              pageNum=pageNum-1;
            }
          }
        });
      },
    );
  }
//线下支付申请
  Future<void> sureDepositRequest(String waybillId,int status) async {

  }
  //获取IM的uid
  void getUid(String waybillId) async {

  }
  ScrollController _scrollController = ScrollController();
  @override
  void dispose() {
    // 释放控制器资源
    _scrollController.dispose();
    super.dispose();
  }

// 模拟加载更多数据的方法
  void onReachBottom() {
    setState(() {
      pageNum=pageNum+1;
      getAllOrderListAction();
    });

    // 在这里可以执行加载更多数据的逻辑
  }

  void getLocation() async {
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    print(position);
    print("1111");
    setState(() {
      Latitude=position.latitude;
      Longitude=position.longitude;
      checkGeofence(Latitude,Longitude);
    });
  }

  Future<void> checkGeofence(double Latitude,double Longitude ) async {
    // 假设这是你的地理围栏的中心和半径
    double fenceLatitude = 37.774934;
    double fenceLongitude = -122.419417;
    double fenceRadius = 10.0; // 单位是公里

    double distance = await Geolocator.distanceBetween(
      Latitude,
      Longitude,
      fenceLatitude,
      fenceLongitude,
    );

    if (distance <= fenceRadius * 1000) {
      print('你在地理围栏范围内');
    } else {
      print('你不在地理围栏范围内');
    }
  }
  BaiduLocationIOSOption initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
        coordType: BMFLocationCoordType.bd09ll,
        BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL',
        desiredAccuracy: BMFDesiredAccuracy.best);
    return options;
  }
  void _locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    Map iosMap = initIOSOptions().getMap();
    Map androidMap = initAndroidOptions().getMap();

    _suc = await _myLocPlugin.prepareLoc(androidMap, iosMap);
    print('设置定位参数：$iosMap');
  }
  /// 启动定位
  Future<void> _startLocation() async {
    if (LocalPlatform().isIOS) {
      _suc = await _myLocPlugin
          .singleLocation({'isReGeocode': true, 'isNetworkState': true});
      print('开始单次定位：$_suc');
    } else if (LocalPlatform().isAndroid) {
      _suc = await _myLocPlugin.startLocation();
    }
  }
  /// 设置地图参数
  BaiduLocationAndroidOption initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        coorType: 'bd09ll',
        locationMode: BMFLocationMode.hightAccuracy,
        isNeedAddress: true,
        isNeedAltitude: true,
        isNeedLocationPoiList: true,
        isNeedNewVersionRgc: true,
        isNeedLocationDescribe: true,
        openGps: true,
        locationPurpose: BMFLocationPurpose.sport,
        coordType: BMFLocationCoordType.bd09ll);
    return options;
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return EasyRefresh(
      header:
      ClassicHeader(
        dragText: '下拉刷新',
        armedText: '准备释放',
        readyText: '加载中...',
        processingText: '加载中...',
        processedText: '刷新成功',
        noMoreText: '暂无更多',
        failedText: '刷新失败',
        messageText: '刷新时间 %T',
      ),
      footer: ClassicFooter(
        dragText: '加载更多',
        armedText: '准备释放',
        readyText: '加载中...',
        processingText: '加载中...',
        processedText: '加载成功',
        noMoreText: '暂无更多',
        failedText: '加载失败',
        messageText: '加载时间 %T',
      ),
      onRefresh: _onRefresh,
      onLoad:dataList.length>pageNum*20-1?onReachBottom:null,
      child:
      Container(

      color: Color.fromRGBO(248, 248, 248, 1),
      child:  ListView(

        children: [

          Container(
            height:screenSize.height-180.h,

    child:dataList.isEmpty?
    BrnAbnormalStateWidget(
      img: Image.asset(
        'lib/Images/OrderList/找货暂无货源.png',
        scale: 3.0,
      ),
      content: '您的账号暂无运输中的运单',
    ):
    ListView.separated(

      shrinkWrap:true,
      itemCount: dataList.length,
      itemBuilder: (BuildContext context, int index) {

        return  GestureDetector(
          child: Container(

            margin: EdgeInsets.only(left: 8.w,right: 8.w),
            padding: EdgeInsets.only(bottom: 11.h,right: 9.w),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child:Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [

                        if( dataList[index]['contractStatus']==2)
                          BrnTagCustom(
                            tagText:dataList[index]['contractMode']=="DRIVER"?"货主待确认":"司机待确认",
                            backgroundColor: Color.fromRGBO(7, 171, 111, 0.5),
                            textPadding:EdgeInsets.only(left: 8.w,right: 8.w,top: 2.h,bottom: 2.h),
                            fontSize: 12.sp,
                            tagBorderRadius: BorderRadius.only(topLeft: Radius.circular(10),bottomRight: Radius.circular(10) ),
                          ),
                        if(dataList[index]['contractStatus']==1&&dataList[index]['driverStatus']==0)
                          BrnTagCustom(
                            tagText:'确认已装货',
                            backgroundColor: Color.fromRGBO(154, 154, 154, 0.5),
                            textPadding:EdgeInsets.only(left: 8.w,right: 8.w,top: 2.h,bottom: 2.h),
                            fontSize: 12.sp,
                            tagBorderRadius: BorderRadius.only(topLeft: Radius.circular(10),bottomRight: Radius.circular(10) ),
                          ),
                        if(dataList[index]['contractStatus']==1&&dataList[index]['driverStatus']==1)
                          BrnTagCustom(
                            tagText:'确认已卸货',
                            backgroundColor: Color.fromRGBO(154, 154, 154, 0.5),
                            textPadding:EdgeInsets.only(left: 8.w,right: 8.w,top: 2.h,bottom: 2.h),
                            fontSize: 12.sp,
                            tagBorderRadius: BorderRadius.only(topLeft: Radius.circular(10),bottomRight: Radius.circular(10) ),
                          ),

                        if(dataList[index]['deliveryStatus']==0&&dataList[index]['driverStatus']==2)
                          BrnTagCustom(
                            tagText:'待货主完成',
                            backgroundColor: Color.fromRGBO(154, 154, 154, 0.5),
                            textPadding:EdgeInsets.only(left: 8.w,right: 8.w,top: 2.h,bottom: 2.h),
                            fontSize: 12.sp,
                            tagBorderRadius: BorderRadius.only(topLeft: Radius.circular(10),bottomRight: Radius.circular(10) ),
                          ),

                        SizedBox(width:8.w,),
                        if(dataList[index]['invoiceType']==1)
                          Image.asset("lib/Images/OrderList/专票标签.png",width:40.w ,height: 18.h,),
                        if(dataList[index]['category']==1)
                          Image.asset("lib/Images/OrderList/分配单标签.png",width:50.w ,height: 16.h,),
                      ],
                    ),

                    if(dataList[index]['riskStatus']==1)
                      Image.asset("lib/Images/OrderList/异常运单.png",width:70.w ,height:20.h,),
                  ],


                ),
                // SizedBox(height: 8.h,),


                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SizedBox(width: 10.w,),
                    Column(
                      children: [

                        Image.asset("lib/Images/OrderList/装货点icon.png",width:20.w ,height:20.h,),
                        Image.asset("lib/Images/OrderList/垂直虚线.png",width:13.w ,height:20.h,),
                        if(dataList[index]['goodsInfo']['loadPlaceInfo'].length==2)
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Image.asset("lib/Images/OrderList/装货点icon.png",width:20.w ,height:20.h,),
                              Image.asset("lib/Images/OrderList/垂直虚线.png",width:18.w ,height:20.h,),
                            ],
                          ),
                        if(dataList[index]['goodsInfo']['unloadPlaceInfo'].length==2)
                          Column(
                            children: [
                              Image.asset("lib/Images/OrderList/卸货点icon.png",width:20.w ,height:20.h,),
                              Image.asset("lib/Images/OrderList/垂直虚线.png",width:18.w ,height:20.h,),
                            ],
                          ),
                        Image.asset("lib/Images/OrderList/卸货点icon.png",width:20.w ,height:20.h,),
                      ],
                    ),
                    SizedBox(width: 4.w,),

                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 8.h,),
                        Row(
                          children: [
                            Container(
                              constraints: BoxConstraints(
                                maxWidth:170.w, // 限制文本最大宽度
                              ),
                              child:
                              Text(dataList[index]['goodsInfo']['loadPlaceInfo'][0]['city']+" "+dataList[index]['goodsInfo']['loadPlaceInfo'][0]['county'],style: TextStyle(color: Colors.black,overflow: TextOverflow.ellipsis,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                            ),
                            SizedBox(width: 4.w,),
                            Container(
                              constraints: BoxConstraints(
                                maxWidth:screenSize.width-220.w, // 限制文本最大宽度
                              ),
                              child: Text(dataList[index]['goodsInfo']['loadDay']+dataList[index]['goodsInfo']['loadTime']+"点装货",overflow: TextOverflow.ellipsis,style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                            ),

                          ],
                        ),
                        Container(
                          constraints: BoxConstraints(
                            maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                          ),
                          child: Text(dataList[index]['goodsInfo']['loadPlaceInfo'][0]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),   overflow: TextOverflow.ellipsis,),

                        ),

                        if(dataList[index]['goodsInfo']['loadPlaceInfo'].length==2)
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(height: 8.h,),
                              Container(
                                constraints: BoxConstraints(
                                  maxWidth:170.w, // 限制文本最大宽度
                                ),
                                child:Text(dataList[index]['goodsInfo']['loadPlaceInfo'][1]['city']+" "+dataList[index]['goodsInfo']['loadPlaceInfo'][1]['county'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,),

                              ),
                              Container(
                                constraints: BoxConstraints(
                                  maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                                ),
                                child: Text(dataList[index]['goodsInfo']['loadPlaceInfo'][1]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),overflow: TextOverflow.ellipsis,),

                              ),
                            ],
                          ),
                        SizedBox(height:8.h,),
                        if(dataList[index]['goodsInfo']['unloadPlaceInfo'].length==2)
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                constraints: BoxConstraints(
                                  maxWidth:170.w, // 限制文本最大宽度
                                ),
                                child: Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['city']+" "+dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['county'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,),

                              ),
                              Container(
                                constraints: BoxConstraints(
                                  maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                                ),
                                child: Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),overflow: TextOverflow.ellipsis,),
                              ),

                              SizedBox(height:8.h,),
                            ],
                          ),
                        Row(
                          children:[
                            dataList[index]['goodsInfo']['unloadPlaceInfo'].length==2?
                            Container(
                                constraints: BoxConstraints(
                                  maxWidth:170.w, // 限制文本最大宽度
                                ),
                                child: Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][1]['city']+" "+dataList[index]['goodsInfo']['unloadPlaceInfo'][1]['county'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,)
                            )
                                :
                            Container(
                              constraints: BoxConstraints(
                                maxWidth:170.w, // 限制文本最大宽度
                              ),
                              child:  Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['city']+" "+dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['county'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,),
                            ),

                            SizedBox(width: 4.w,),
                            if (dataList[index]['goodsInfo']['unloadDay'] != null)
                              Container(
                                constraints: BoxConstraints(
                                  maxWidth:screenSize.width-220.w, // 限制文本最大宽度
                                ),
                                child: Text(dataList[index]['goodsInfo']['unloadDay']+" "+dataList[index]['goodsInfo']['unloadTime']+"点卸货",overflow: TextOverflow.ellipsis,style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),

                              ) ,                                  ],
                        ),
                        dataList[index]['goodsInfo']['unloadPlaceInfo'].length==2?
                        Container(
                            constraints: BoxConstraints(
                              maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                            ),
                            child:Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][1]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),overflow: TextOverflow.ellipsis,)
                        )
                            :
                        Container(
                          constraints: BoxConstraints(
                            maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                          ),
                          child:  Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),overflow: TextOverflow.ellipsis,),
                        ),

                      ],
                    ),

                  ],
                ),
                SizedBox(height: 4.h,),
                Row(
                  children: [
                    SizedBox(width:10.w,),
                    Text( dataList[index]['goodsInfo']['cargoInfo'][0]['cargoName'].toString()+","+dataList[index]['goodsInfo']['cargoInfo'][0]['packageType'].toString(),style: TextStyle(color:MyColors.textColor,fontSize: 13.sp ),),
                    if(dataList[index]['goodsInfo']['cargoInfo'][0]['cargoWeight']!=null)
                      Text( ","+dataList[index]['goodsInfo']['cargoInfo'][0]['cargoWeight'].toString()+"吨",style: TextStyle(color:MyColors.textColor,fontSize: 13.sp ),) ,
                    if(dataList[index]['goodsInfo']['cargoInfo'][0]['cargoVolume']!=null)
                      Text( ","+dataList[index]['goodsInfo']['cargoInfo'][0]['cargoVolume'].toString()+"方",style: TextStyle(color:MyColors.textColor,fontSize: 13.sp ),)
                  ],
                ),
                SizedBox(height: 8.h,),
                Container(
                  margin: EdgeInsets.only(left: 20.w,right: 20.w),
                  height: 1.h,
                  color: Color.fromRGBO(245, 243, 243, 1),
                ),
                SizedBox(height: 8.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        SizedBox(width: 8.w,),
                        Container(
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(10))),
                          child: ClipOval(
                            child: dataList[index]['shipperInfo']['avatarPath']!=""&&dataList[index]['shipperInfo']['avatarPath']!=null?Image.network(
                              MyServiceUrl.imgHeader + dataList[index]['shipperInfo']['avatarPath'],
                              width: 36.w,
                              height: 36.h,
                              fit: BoxFit.cover,
                            ):Image.asset("lib/Images/login/默认头像.jpeg",width: 36.w,height: 36.h, fit: BoxFit.cover,),
                          ),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(width: 8.w,),
                                Text(dataList[index]['shipperInfo']['realName'],style: TextStyle(color: Colors.black,fontSize: 13.sp ),),
                              ],
                            ),
                            if(dataList[index]['haulierInfo']!=null)
                              Row(
                                children: [
                                  SizedBox(width: 4.w,),
                                  Text(dataList[index]['haulierInfo']['name'].toString(),style: TextStyle(color:MyColors.textColor,fontSize: 12.sp ),)
                                ],
                              ),


                          ],
                        ),

                      ],
                    ),
                    Row(
                      children: [
                        GestureDetector(
                          child: Image.asset("lib/Images/OrderList/IMicon.png",width: 24.w,height: 24.h,),
                          onTap: (){
                            getUid(dataList[index]['waybillId']);

                          },
                        ),
                        SizedBox(width: 8.w,),
                        GestureDetector(
                          child: Image.asset("lib/Images/OrderList/电话联系icon.png",width: 24.w,height: 24.h,),
                          onTap: (){
                            _makePhoneCall(dataList[index]['drvPhoneNum']);
                          },
                        ),
                      ],
                    )


                  ],
                ),
                SizedBox(height:8.h,),
                Container(
                  margin: EdgeInsets.only(left: 20.w,right: 20.w),
                  height: 1.h,
                  color: Color.fromRGBO(245, 243, 243, 1),
                ),
                SizedBox(height:8.h,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    dataList[index]['insuranceStatus']==1?
                    Image.asset("lib/Images/OrderList/保险icon.png",width: 50.w,height: 20.h,):SizedBox(),
                    Row(
                      children: [

                        RichText(
                          text:TextSpan(children: [
                            if(dataList[index]['depositType']!=-1)
                              TextSpan(
                                  text: messages["订金"],
                                  style: TextStyle(fontSize: 11.sp, color: Colors.black)),
                            if(dataList[index]['depositType']!=-1)
                              TextSpan(
                                  text: '¥'+(dataList[index]['deposit']).toString(),
                                  style: TextStyle(fontSize: 11.sp, color: Color.fromRGBO(231, 112, 27, 0.85))),
                            if(dataList[index]['depositType']!=-1)
                              TextSpan(
                                  text: dataList[index]['depositStatus']==0?'(待支付)':dataList[index]['depositStatus']==2?"(已退回)":dataList[index]['depositStatus']==1?"(平台监管中)":"(已支付到货主)",
                                  style: TextStyle(fontSize: 11.sp, color: Colors.black)),
                            TextSpan(
                                text: messages["运费"],
                                style: TextStyle(fontSize: 11.sp, color: Colors.black)),
                            if(dataList[index]['freight']!="0.000")
                              TextSpan(
                                  text: '¥'+dataList[index]['freight'],
                                  style: TextStyle(fontSize: 11.sp, color: Color.fromRGBO(231, 112, 27, 0.85))),
                            if(dataList[index]['price']!="0.000"&&dataList[index]['freight']=="0.000")
                              TextSpan(
                                  text: '¥'+dataList[index]['price'],
                                  style: TextStyle(fontSize: 11.sp, color: Color.fromRGBO(231, 112, 27, 0.85))),
                            TextSpan(
                                text: dataList[index]['freightStatus']==-1?'(线下支付)':dataList[index]['freightStatus']==0?'(待支付)':dataList[index]['freightStatus']==1?"(平台监管中)":dataList[index]['freightStatus']==2?"(支付到司机)":"(已退回到货主)",
                                style: TextStyle(fontSize: 11.sp, color: Colors.black)),
                          ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                SizedBox(height: 8.h,),


                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [

                    if(dataList[index]['deliveryStatus']==0&&dataList[index]['driverStatus']==0&&dataList[index]['contractStatus']==1)
                      Row(
                        children: [
                          SizedBox(width: 8.w,),
                          GestureDetector(
                            child:  Container(
                                width: 85.w,
                                height: 25.h,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(30.0),
                                  border: Border.all(
                                    color: MyColors.themeColor,
                                    width: 1.0,
                                  ),
                                ),
                                child: Center(child: Text("确认已装货",style: TextStyle(fontSize: 13.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
                            ),
                            onTap: ()  {
                              showDialog(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return upLpadCarphotoAlert(dataMap: dataList[index], photoType: 1,);

                                  }
                              );
                            },
                          ),
                        ],
                      ),
                    if(dataList[index]['deliveryStatus']==0&&dataList[index]['driverStatus']==1)
                      Row(
                        children: [
                          SizedBox(width: 8.w,),
                          GestureDetector(
                            child:  Container(
                                width: 85.w,
                                height: 25.h,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(30.0),
                                  border: Border.all(
                                    color: MyColors.themeColor,
                                    width: 1.0,
                                  ),
                                ),
                                child: Center(child: Text("确认已卸货",style: TextStyle(fontSize: 13.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
                            ),
                            onTap: ()  {
                              showDialog(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return upLpadCarphotoAlert(dataMap: dataList[index], photoType: 2,);

                                  }
                              );
                            },
                          ),
                        ],
                      ),
                    if(dataList[index]['driverStatus']==2&&dataList[index]['deliveryStatus']==0)
                      Row(
                        children: [
                          SizedBox(width: 8.w,),
                          GestureDetector(
                            child:  Container(
                                width: 75.w,
                                height: 25.h,
                                decoration: BoxDecoration(
                                  color: MyColors.themeColor,
                                  borderRadius: BorderRadius.circular(30.0),
                                  border: Border.all(
                                    color: MyColors.themeColor,
                                    width: 1.0,
                                  ),
                                ),
                                child: Center(child: Text(dataList[index]['receiptStatus']==0?'上传回单':"查看回单",style: TextStyle(fontSize: 13.sp,color: Colors.white,fontWeight: FontWeight.w600),),)
                            ),
                            onTap: ()  {
                              if(dataList[index]['receiptStatus']==0){
                                Navigator.push( context, FadeRoute(page:UploadPhotoPage(dataMap: dataList[index], uploadType: 3,)));

                              }else{
                                Navigator.push( context, FadeRoute(page:PictureManagement(type: 1,dataMap: dataList[index])));
                              }
                            },
                          ),
                        ],
                      ),

                  ],
                ),

              ],
            ),
          ),

          onTap: () async {
            Navigator.push( context, FadeRoute(page:WaybillDetails(billId: dataList[index]['id'], type: 1,)));


          },
        );


      },
      separatorBuilder: (context, index) { //自定义分割线
        return   Container(
          height: 8.h,
        );
      },


    ),
          ),
          // ),
          // ),
        ],
      ),
      ),
    );


  }
}

class upLpadCarphotoAlert extends StatefulWidget {
  const upLpadCarphotoAlert({super.key, required this.dataMap, required this.photoType});
  final Map dataMap;
  final int photoType;
  @override
  State<upLpadCarphotoAlert> createState() => _upLpadCarphotoAlertState();
}

class _upLpadCarphotoAlertState extends State<upLpadCarphotoAlert> {
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Center(
        child: Container(
        decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(10))),
        width: screenSize.width-60.w,
        height: 340.h,
          child: Column(
            children: [
              SizedBox(height: 10.h,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(width: 20.w,),
                  Text(widget.photoType==1?"上传装货照片":"上传卸货照片",style: TextStyle(color: Colors.black,fontSize: 18.sp,decoration: TextDecoration.none,fontWeight: FontWeight.w100),),
                IconButton(onPressed: (){Navigator.pop(context);}, icon: Icon(Icons.close,size: 30,color: MyColors.authTipColor,)),
                ],
              ),
              Center(
                child: Container(
                  width: 209.w,
                  child: Text(widget.photoType==1?"请上传装货照片！照片需清晰，车牌无遮挡，含货物及现场照片。完善凭证照片有利于及时收取运费！":"请上传卸货照片！照片需清晰，车牌无遮挡，含货物及现场照片。完善凭证照片有利于及时收取运费！",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp,decoration: TextDecoration.none,fontWeight: FontWeight.w100),),
                ),
              ),
              Image.asset("lib/Images/OrderList/上传装货照片示例.png",width: 169.w,height: 169.h,),
              Text("示例：能看清车牌的现场图",style: TextStyle(color: MyColors.hintColor,fontSize: 12.sp,decoration: TextDecoration.none),),
              Divider(height: 16.h,color: MyColors.backgreyColor,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(),
                  GestureDetector(
                    child: Container(
                      width: 100.w,
                      height:30.h,
                      child: Center(
                        child: Text("我再想想",style: TextStyle(color: Colors.black,fontSize: 14.sp,decoration: TextDecoration.none,fontWeight: FontWeight.w100),),
                      ),
                    ),
                    onTap: (){Navigator.pop(context);},
                  ),
                  Container(width: 1.w,height: 30.h,color: MyColors.backgreyColor,),
                  GestureDetector(
                    child: Container(
                      width: 100.w,
                      height: 30.h,
                      child: Center(
                        child: Text("立即上传",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp,decoration: TextDecoration.none,fontWeight: FontWeight.w100),),
                      ),
                    ),
                    onTap: () {
                      Navigator.pop(context);
                      Navigator.push(context, FadeRoute(page: UploadPhotoPage(
                        uploadType: widget.photoType,
                        dataMap: widget.dataMap,)));
                    }
                  ),
                  SizedBox(),
                ],
              ),
            ],
          ),
        ),

    );
  }
}
